<!DOCTYPE HTML>
<html lang="zh-Hans" class="sidebar-visible no-js light">
    <head>
        <!-- Book generated using mdBook -->
        <meta charset="UTF-8">
        <title>用rust从零开发一套web框架：day3 - Rust 优秀博文</title>


        <!-- Custom HTML head -->
        
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="theme-color" content="#ffffff" />

        <link rel="icon" href="../../favicon.svg">
        <link rel="shortcut icon" href="../../favicon.png">
        <link rel="stylesheet" href="../../css/variables.css">
        <link rel="stylesheet" href="../../css/general.css">
        <link rel="stylesheet" href="../../css/chrome.css">
        <link rel="stylesheet" href="../../css/print.css" media="print">

        <!-- Fonts -->
        <link rel="stylesheet" href="../../FontAwesome/css/font-awesome.css">
        <link rel="stylesheet" href="../../fonts/fonts.css">

        <!-- Highlight.js Stylesheets -->
        <link rel="stylesheet" href="../../highlight.css">
        <link rel="stylesheet" href="../../tomorrow-night.css">
        <link rel="stylesheet" href="../../ayu-highlight.css">

        <!-- Custom theme stylesheets -->

    </head>
    <body>
        <!-- Provide site root to javascript -->
        <script type="text/javascript">
            var path_to_root = "../../";
            var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
        </script>

        <!-- Work around some values being stored in localStorage wrapped in quotes -->
        <script type="text/javascript">
            try {
                var theme = localStorage.getItem('mdbook-theme');
                var sidebar = localStorage.getItem('mdbook-sidebar');

                if (theme.startsWith('"') && theme.endsWith('"')) {
                    localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
                }

                if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
                    localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
                }
            } catch (e) { }
        </script>

        <!-- Set the theme before any content is loaded, prevents flash -->
        <script type="text/javascript">
            var theme;
            try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
            if (theme === null || theme === undefined) { theme = default_theme; }
            var html = document.querySelector('html');
            html.classList.remove('no-js')
            html.classList.remove('light')
            html.classList.add(theme);
            html.classList.add('js');
        </script>

        <!-- Hide / unhide sidebar before it is displayed -->
        <script type="text/javascript">
            var html = document.querySelector('html');
            var sidebar = 'hidden';
            if (document.body.clientWidth >= 1080) {
                try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
                sidebar = sidebar || 'visible';
            }
            html.classList.remove('sidebar-visible');
            html.classList.add("sidebar-" + sidebar);
        </script>

        <nav id="sidebar" class="sidebar" aria-label="Table of contents">
            <div class="sidebar-scrollbox">
                <ol class="chapter"><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">1.</strong> 类型系统</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../01_类型系统/Rust_Concept_Clarification_Deref_vs_AsRef_vs_Borrow_vs_Cow/Rust_Concept_Clarification_Deref_vs_AsRef_vs_Borrow_vs_Cow.html"><strong aria-hidden="true">1.1.</strong> Rust Concept Clarification Deref vs AsRef vs Borrow vs Cow</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Rust_Concept_Clarification_Deref_vs_AsRef_vs_Borrow_vs_Cow/Deref_AsRef_Borrow_Cow释义.html"><strong aria-hidden="true">1.2.</strong> Deref AsRef Borrow Cow 释义</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Rust的Borrow和AsRef：让你的代码用起来像呼吸一样自然/Rust的Borrow和AsRef：让你的代码用起来像呼吸一样自然.html"><strong aria-hidden="true">1.3.</strong> Rust的Borrow和AsRef：让你的代码用起来像呼吸一样自然</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Rust的Cow类型有什么用？详解Cow及其用途/Rust的Cow类型有什么用？详解Cow及其用途.html"><strong aria-hidden="true">1.4.</strong> Rust的Cow类型有什么用？详解Cow及其用途</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/判别Fn、FnMut、FnOnce的标准/判别Fn、FnMut、FnOnce的标准.html"><strong aria-hidden="true">1.5.</strong> 判别Fn、FnMut、FnOnce的标准</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/一行代码告诉你内部可变性的真相(UnsafeCell)/一行代码告诉你内部可变性的真相(UnsafeCell).html"><strong aria-hidden="true">1.6.</strong> 一行代码告诉你内部可变性的真相(UnsafeCell)</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Tour_of_Rust's_Standard_Library_Traits/Tour_of_Rust's_Standard_Library_Traits.html"><strong aria-hidden="true">1.7.</strong> Tour of Rust's Standard Library Traits</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/逆变、协变与子类型，以及Rust/逆变、协变与子类型，以及Rust.html"><strong aria-hidden="true">1.8.</strong> 逆变、协变与子类型，以及Rust</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Rust自引用结构、Pin与Unpin/Rust自引用结构、Pin与Unpin.html"><strong aria-hidden="true">1.9.</strong> Rust自引用结构、Pin与Unpin</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/为什么Rust需要Pin,Unpin/为什么Rust需要Pin,Unpin.html"><strong aria-hidden="true">1.10.</strong> 译：为什么 Rust 需要 Pin, Unpin ？</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/定海神针Pin和Unpin/定海神针Pin和Unpin.html"><strong aria-hidden="true">1.11.</strong> 译：定海神针 Pin 和 Unpin</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/sizedness-in-rust/sizedness-in-rust.html"><strong aria-hidden="true">1.12.</strong> Sizedness in Rust</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Rust生命周期集大成者PhantomData〈T〉/Rust生命周期集大成者PhantomData〈T〉.html"><strong aria-hidden="true">1.13.</strong> Rust生命周期集大成者 PhantomData&lt;T&gt;</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：用Rust做类型体操_Part_0.html"><strong aria-hidden="true">1.14.</strong> 数据库表达式执行的黑魔法：用Rust做类型体操 Part 0</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：GAT实现引用类型关联_Part_1.html"><strong aria-hidden="true">1.15.</strong> 数据库表达式执行的黑魔法：GAT实现引用类型关联 Part 1</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：用HRTB写bound_Part_2.html"><strong aria-hidden="true">1.16.</strong> 数据库表达式执行的黑魔法：用HRTB写bound Part 2</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：用Rust做类型体操之用宏展开重复代码_Part_3_&_4.html"><strong aria-hidden="true">1.17.</strong> 数据库表达式执行的黑魔法：用Rust做类型体操之用宏展开重复代码 Part 3 & 4</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：与Rust编译器斗智斗勇之表达式向量化_Part_5_&_6.html"><strong aria-hidden="true">1.18.</strong> 数据库表达式执行的黑魔法：与Rust编译器斗智斗勇之表达式向量化 Part 5 & 6</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：在Rust中用宏关联逻辑类型和实际类型_Part_7.html"><strong aria-hidden="true">1.19.</strong> 数据库表达式执行的黑魔法：在Rust中用宏关联逻辑类型和实际类型 Part 7</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">2.</strong> 生命周期</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../02_生命周期/Rust中的生命周期——从StrSplit实例说开去/Rust中的生命周期——从StrSplit实例说开去.html"><strong aria-hidden="true">2.1.</strong> Rust中的生命周期——从StrSplit实例说开去</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/与ChatGPT深度对话来学Rust生命周期/与ChatGPT深度对话来学Rust生命周期.html"><strong aria-hidden="true">2.2.</strong> 与ChatGPT深度对话来学Rust生命周期</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/进击的Rust生命周期——early_bound与late_bound（1）/进击的Rust生命周期——early_bound与late_bound（1）.html"><strong aria-hidden="true">2.3.</strong> 进击的Rust生命周期——early_bound与late_bound（1）</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/进击的Rust生命周期——early_bound与late_bound（2）/进击的Rust生命周期——early_bound与late_bound（2）.html"><strong aria-hidden="true">2.4.</strong> 进击的Rust生命周期——early_bound与late_bound（2）</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/进击的Rust生命周期——一力降十会的MIR（1）/进击的Rust生命周期——一力降十会的MIR（1）.html"><strong aria-hidden="true">2.5.</strong> 进击的Rust生命周期——一力降十会的MIR（1）</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/进击的Rust生命周期——一力降十会的MIR（2）/进击的Rust生命周期——一力降十会的MIR（2）.html"><strong aria-hidden="true">2.6.</strong> 进击的Rust生命周期——一力降十会的MIR（2）</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/Common_Rust_Lifetime_Misconceptions/Common_Rust_Lifetime_Misconceptions.html"><strong aria-hidden="true">2.7.</strong> Common Rust Lifetime Misconceptions</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/Rust生命周期常见误区/Rust生命周期常见误区.html"><strong aria-hidden="true">2.8.</strong> 译：Rust生命周期常见误区</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">3.</strong> 无畏并发</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../05_无畏并发/简单写个Rust无锁队列/简单写个Rust无锁队列.html"><strong aria-hidden="true">3.1.</strong> 简单写个Rust无锁队列</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/进击的Rust多线程——混合自旋锁/进击的Rust多线程——混合自旋锁.html"><strong aria-hidden="true">3.2.</strong> 进击的Rust多线程——混合自旋锁</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/An_unsafe_tour_of_Rust's_Send_and_Sync/An_unsafe_tour_of_Rust's_Send_and_Sync.html"><strong aria-hidden="true">3.3.</strong> An unsafe tour of Rust's Send and Sync</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/进击的Rust多线程——Send与Sync/进击的Rust多线程——Send与Sync.html"><strong aria-hidden="true">3.4.</strong> 进击的Rust多线程——Send与Sync</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/进击的Rust多线程——离经叛道的PhantomData/进击的Rust多线程——离经叛道的PhantomData.html"><strong aria-hidden="true">3.5.</strong> 进击的Rust多线程——离经叛道的PhantomData</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/Rust_Async_Pin概念解析/Rust_Async_Pin概念解析.html"><strong aria-hidden="true">3.6.</strong> Rust Async: Pin概念解析</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/Rust和C++的并发库对比/Rust和C++的并发库对比.html"><strong aria-hidden="true">3.7.</strong> 译：Rust 和 C++ 的并发库对比</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/Rust原子类型和内存排序/Rust原子类型和内存排序.html"><strong aria-hidden="true">3.8.</strong> Rust原子类型和内存排序</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">4.</strong> 网络编程</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../06_网络编程/从编解码层面理解WebSocket_手写一个WebSocket/从编解码层面理解WebSocket_手写一个WebSocket.html"><strong aria-hidden="true">4.1.</strong> 从编解码层面理解WebSocket 手写一 个WebSocket</a></li><li class="chapter-item expanded "><a href="../../06_网络编程/透过Rust探索系统的本原：网络篇/透过Rust探索系统的本原：网络篇.html"><strong aria-hidden="true">4.2.</strong> 透过Rust探索系统的本原：网络篇</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">5.</strong> 轮子系列</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../07_轮子系列/700行Rust写一个内存分配器/700行Rust写一个内存分配器.html"><strong aria-hidden="true">5.1.</strong> 700行Rust写一个内存分配器</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/Rust：网络库的实现思路/Rust：网络库的实现思路.html"><strong aria-hidden="true">5.2.</strong> Rust：网络库的实现思路</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/Rust异步运行时基础部件/Rust异步运行时基础部件.html"><strong aria-hidden="true">5.3.</strong> Rust异步运行时基础部件</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/使用Rust+epoll编写异步IO框架/使用Rust+epoll编写异步IO框架（1）.html"><strong aria-hidden="true">5.4.</strong> 使用Rust+epoll编写异步IO框架（1）</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/使用Rust+epoll编写异步IO框架/使用Rust+epoll编写异步IO框架（2）.html"><strong aria-hidden="true">5.5.</strong> 使用Rust+epoll编写异步IO框架（2）</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/使用Rust+epoll编写异步IO框架/使用Rust+epoll编写异步IO框架（3）.html"><strong aria-hidden="true">5.6.</strong> 使用Rust+epoll编写异步IO框架（3）</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/用rust从零开发一套web框架/用rust从零开发一套web框架：day1.html"><strong aria-hidden="true">5.7.</strong> 用rust从零开发一套web框架：day1</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/用rust从零开发一套web框架/用rust从零开发一套web框架：day2.html"><strong aria-hidden="true">5.8.</strong> 用rust从零开发一套web框架：day2</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/用rust从零开发一套web框架/用rust从零开发一套web框架：day3.html" class="active"><strong aria-hidden="true">5.9.</strong> 用rust从零开发一套web框架：day3</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/用rust从零开发一套web框架/用rust从零开发一套web框架：day4.html"><strong aria-hidden="true">5.10.</strong> 用rust从零开发一套web框架：day4</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/用rust从零开发一套web框架/用rust从零开发一套web框架：day5.html"><strong aria-hidden="true">5.11.</strong> 用rust从零开发一套web框架：day5</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">6.</strong> 奇技淫巧</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../08_奇技淫巧/Copy-On-Write是不是优化？/Copy-On-Write是不是优化？.html"><strong aria-hidden="true">6.1.</strong> 译：Copy-On-Write是不是优化？</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/揭秘神奇的Rust_Axum风格的函数实现/揭秘神奇的Rust_Axum风格的函数实现.html"><strong aria-hidden="true">6.2.</strong> 译：揭秘神奇的 Rust Axum 风格的函数实现</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/“变长参数”函数与回调/“变长参数”函数与回调.html"><strong aria-hidden="true">6.3.</strong> “变长参数”函数与回调</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/Rust字符串格式化的幕后：format_args!()/Rust字符串格式化的幕后：format_args!().html"><strong aria-hidden="true">6.4.</strong> 译：Rust字符串格式化的幕后：format_args!()</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/给Rust带来一点C++特产/给Rust带来一点C++特产.html"><strong aria-hidden="true">6.5.</strong> 给Rust带来一点C++特产</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/一步步实现_Rust_Bevy_ECS_的_System_简化版本/一步步实现_Rust_Bevy_ECS_的_System_简化版本.html"><strong aria-hidden="true">6.6.</strong> 一步步实现 Rust Bevy ECS 的 System 简化版本</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/Exploring_Design_Patterns_in_Rust_with_Algorithmic_Trading_Examples/Exploring_Design_Patterns_in_Rust_with_Algorithmic_Trading_Examples.html"><strong aria-hidden="true">6.7.</strong> Exploring Design Patterns in Rust with Algorithmic Trading Examples</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">7.</strong> 源码分析</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../09_源码分析/Rust并发：bytes源码分析/Rust并发：bytes源码分析.html"><strong aria-hidden="true">7.1.</strong> Rust并发：bytes源码分析</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust并发：标准库Arc源码分析/Rust并发：标准库Arc源码分析.html"><strong aria-hidden="true">7.2.</strong> Rust并发：标准库Arc源码分析</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust并发：标准库sync_Once源码分析/Rust并发：标准库sync_Once源码分析.html"><strong aria-hidden="true">7.3.</strong> Rust并发：标准库sync::Once源码分析</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust源码阅读：引用计数Rc/Rust源码阅读：引用计数Rc.html"><strong aria-hidden="true">7.4.</strong> Rust源码阅读：引用计数Rc</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust源码阅读：Cell、RefCell与内部可变性/Rust源码阅读：Cell、RefCell与内部可变性.html"><strong aria-hidden="true">7.5.</strong> Rust源码阅读： Cell、RefCell与内部可变性</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/关于_Rust_的_UnsafeCell、Cell_与_RefCell/关于_Rust_的_UnsafeCell、Cell_与_RefCell.html"><strong aria-hidden="true">7.6.</strong> 关于 Rust 的 UnsafeCell、Cell 与 RefCell</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust_Async_async-stream源码分析/Rust_Async_async-stream源码分析.html"><strong aria-hidden="true">7.7.</strong> Rust Async: async-stream源码分析</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/走进Tokio的异步世界/走进Tokio的异步世界.html"><strong aria-hidden="true">7.8.</strong> 走进 Tokio 的异步世界</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/tokio.rs_runtime的实现/tokio.rs_runtime的实现.html"><strong aria-hidden="true">7.9.</strong> tokio.rs runtime 的实现</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Tokio_internals/Tokio_internals.html"><strong aria-hidden="true">7.10.</strong> Tokio internals</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Tokio_internals/译文：Tokio內部机制.html"><strong aria-hidden="true">7.11.</strong> 译：Tokio 内部机制</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust_Axum_HTTP_框架的架构分析/Rust_Axum_HTTP_框架的架构分析.html"><strong aria-hidden="true">7.12.</strong> Rust Axum HTTP 框架的架构分析</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/安利一个Rust_Game_Engine：Bevy--ECS部分/安利一个Rust_Game_Engine：Bevy--ECS部分.html"><strong aria-hidden="true">7.13.</strong> 安利一个Rust Game Engine：Bevy--ECS部分</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Tokio_解析之任务调度/Tokio_解析之任务调度.html"><strong aria-hidden="true">7.14.</strong> Tokio 解析之任务调度</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">8.</strong> 生态观察</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../11_生态观察/Rust_web_frameworks_have_subpar_error_reporting/Rust_web_frameworks_have_subpar_error_reporting.html"><strong aria-hidden="true">8.1.</strong> Rust web frameworks have subpar error reporting</a></li><li class="chapter-item expanded "><a href="../../11_生态观察/SeaORM：要做Rust版本的ActiveRecord/SeaORM：要做Rust版本的ActiveRecord.html"><strong aria-hidden="true">8.2.</strong> SeaORM：要做Rust版本的ActiveRecord</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">9.</strong> 死灵终极</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_总述.html"><strong aria-hidden="true">9.1.</strong> 译：Learn Rust the Dangerous Way 总述</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_0.html"><strong aria-hidden="true">9.2.</strong> 译：Learn Rust the Dangerous Way 0</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_1.html"><strong aria-hidden="true">9.3.</strong> 译：Learn Rust the Dangerous Way 1</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_2.html"><strong aria-hidden="true">9.4.</strong> 译：Learn Rust the Dangerous Way 2</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_3.html"><strong aria-hidden="true">9.5.</strong> 译：Learn Rust the Dangerous Way 3</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_4.html"><strong aria-hidden="true">9.6.</strong> 译：Learn Rust the Dangerous Way 4</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_5.html"><strong aria-hidden="true">9.7.</strong> 译：Learn Rust the Dangerous Way 5</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Unsafe_Rust_随堂小测/Unsafe_Rust_随堂小测（一）.html"><strong aria-hidden="true">9.8.</strong> Unsafe Rust 随堂小测（一）</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Unsafe_Rust_随堂小测/Unsafe_Rust_随堂小测（二）.html"><strong aria-hidden="true">9.9.</strong> Unsafe Rust 随堂小测（二）</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Unsafe_Rust_随堂小测/Unsafe_Rust_随堂小测（三）.html"><strong aria-hidden="true">9.10.</strong> Unsafe Rust 随堂小测（三）</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Unsafe_Rust_随堂小测/Unsafe_Rust_随堂小测参考答案.html"><strong aria-hidden="true">9.11.</strong> Unsafe Rust 随堂小测参考答案</a></li></ol></li></ol>
            </div>
            <div id="sidebar-resize-handle" class="sidebar-resize-handle"></div>
        </nav>

        <div id="page-wrapper" class="page-wrapper">

            <div class="page">
                                <div id="menu-bar-hover-placeholder"></div>
                <div id="menu-bar" class="menu-bar sticky bordered">
                    <div class="left-buttons">
                        <button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
                            <i class="fa fa-bars"></i>
                        </button>
                        <button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
                            <i class="fa fa-paint-brush"></i>
                        </button>
                        <ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
                            <li role="none"><button role="menuitem" class="theme" id="light">Light (default)</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
                        </ul>
                        <button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
                            <i class="fa fa-search"></i>
                        </button>
                    </div>

                    <h1 class="menu-title">Rust 优秀博文</h1>

                    <div class="right-buttons">
                        <a href="../../print.html" title="Print this book" aria-label="Print this book">
                            <i id="print-button" class="fa fa-print"></i>
                        </a>

                    </div>
                </div>

                <div id="search-wrapper" class="hidden">
                    <form id="searchbar-outer" class="searchbar-outer">
                        <input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
                    </form>
                    <div id="searchresults-outer" class="searchresults-outer hidden">
                        <div id="searchresults-header" class="searchresults-header"></div>
                        <ul id="searchresults">
                        </ul>
                    </div>
                </div>

                <!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
                <script type="text/javascript">
                    document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
                    document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
                    Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
                        link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
                    });
                </script>

                <div id="content" class="content">
                    <main>
                        <h1 id="用-rust-从零开发一套-web-框架day3"><a class="header" href="#用-rust-从零开发一套-web-框架day3">用 rust 从零开发一套 web 框架：day3</a></h1>
<p><a href="https://juejin.cn/user/677714513628055/posts">linken_coding</a></p>
<p>2022-12-055,241阅读10分钟</p>
<p>专栏： </p>
<p>rust从零开发轮子系列</p>
<p>开启掘金成长之旅！这是我参与「掘金日新计划 · 12 月更文挑战」的第7天，<a href="https://juejin.cn/post/7167294154827890702">点击查看活动详情</a></p>
<h2 id="金丹初成"><a class="header" href="#金丹初成">金丹初成</a></h2>
<p>在前面一章里，我们对<code>AppContext</code>进行了拓展，同时也对路由的 <code>query</code> 参数进行解析和 <code>hashMap</code> 存储。 现在，我们来搭建动态路由系统，并进行<code>params</code> 参数的解析和存储。</p>
<h2 id="routernode-动态路由节点树"><a class="header" href="#routernode-动态路由节点树">RouterNode 动态路由节点树</a></h2>
<p>接下来我们实现的动态路由需要具备以下三个功能。</p>
<ol>
<li>参数匹配<code>:</code> 例如 <code>/index/:id/b</code>，可以匹配 <code>/index/c/b</code> 和 <code>/index/go/c</code>。</li>
<li>通配符<code>*</code> 例如 <code>/static/*filepath</code>，可以匹配<code>/static/fav.ico</code>，也可以匹配<code>/static/vue.js</code>，这种模式常用于静态服务器，能够递归地匹配子路径。</li>
<li>无参数路由匹配 例如 <code>http://localhost:3000/admin</code>，可以精准匹配到路由<code>/admin</code>，<code>http://localhost:3000/admin/index</code>则精准匹配到<code>/admin/index</code>。</li>
</ol>
<p>首先设计 Trie 树的结构，作为路由节点树：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>//Trie 树
#[derive(Debug, Clone)]
pub struct RouterNode {
    pub pattern: Option&lt;String&gt;,   // 待匹配路由，例如 /p/:lang
    pub part: Option&lt;String&gt;,      // 路由中的一部分，例如 :lang
    pub children: Vec&lt;RouterNode&gt;, // 子节点，例如 [doc, tutorial, intro]
    pub is_match: bool,            // 是否精确匹配，part 含有 : 或 * 时为true
    pub hooks: Vec&lt;String&gt;,        //中间件钩子函数，暂时用字符串替位
    pub method: Option&lt;String&gt;,    //请求方法
}
<span class="boring">}
</span></code></pre></pre>
<p>接着为这个结构体实现一些方法,比如初始化的 new 方法：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>impl RouterNode {
    pub fn new() -&gt; Self {
        RouterNode {
            pattern: None,
            children: Vec::new(),
            part: None,
            is_match: false,
            hooks: Vec::new(),
            method: None,
        }
    }
}
<span class="boring">}
</span></code></pre></pre>
<p>对于路由来说，最重要的当然是注册与匹配了。开发服务时，注册路由规则，映射 <code>handler</code>。访问时，匹配路由规则，查找到对应的 <code>handler</code>。因此，Trie 树需要支持节点的插入与查询。</p>
<p>插入功能很简单，递归查找每一层的节点，如果没有匹配到当前<code>pattern</code>或者<code>part</code> 的节点，则新建一个。</p>
<p>有一点需要注意，<code>/admin/:id</code> 存在两层节点，第一层为<code>/admin</code>，因为没有参数，所以<code>part</code>和<code>method</code>皆为<code>None</code>。 第二层 即 <code>:id</code>节点，<code>pattern</code> 会设置为<code>/admin/:id</code>。<code>part</code>为<code>:id</code>。</p>
<p>因此，当匹配结束时，我们可以使用 <code>node.pattern</code>、<code>node.part</code>和<code>method</code>是否为 <code>None</code> 来判断路由规则是否匹配成功。例如，<code>/admin/123</code> 能成功匹配到<code>:id</code>，但第一层的<code>/admin</code>节点 的 <code>part</code> 和<code>method</code>值为空，因此匹配失败。接着递归查找下一层。通配符<code>*</code>也是同理。</p>
<p>查询功能，同样也是递归查询每一层的节点，退出规则是，匹配到了<code>*</code>就匹配完成，或者匹配到了(parts/pattern)的节点。</p>
<p>当然，前面说了这么多，还是让人感觉云里雾里，不明所以。</p>
<p>最直接的，还是先看一个简单的插入结果：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>RouterNode {
    pattern: None,
    part: None,
    children: [
        RouterNode {
            pattern: Some(
                &quot;/user&quot;,
            ),
            part: None,
            children: [],
            is_match: false,
            hooks: [],
            method: Some(
                &quot;GET&quot;,
            ),
        },
        RouterNode {
            pattern: Some(
                &quot;/user&quot;,
            ),
            part: None,
            children: [],
            is_match: false,
            hooks: [],
            method: Some(
                &quot;POST&quot;,
            ),
        },
        RouterNode {
            pattern: Some(
                &quot;/admin&quot;,
            ),
            part: None,
            children: [
                RouterNode {
                    pattern: Some(
                        &quot;/admin/:id&quot;,
                    ),
                    part: Some(
                        &quot;:id&quot;,
                    ),
                    children: [],
                    is_match: true,
                    hooks: [],
                    method: Some(
                        &quot;POST&quot;,
                    ),
                },
                RouterNode {
                    pattern: Some(
                        &quot;/admin/*id&quot;,
                    ),
                    part: Some(
                        &quot;*id&quot;,
                    ),
                    children: [],
                    is_match: true,
                    hooks: [],
                    method: Some(
                        &quot;GET&quot;,
                    ),
                },
            ],
            is_match: false,
            hooks: [],
            method: None,
        },
    ],
    is_match: false,
    hooks: [],
    method: None,
}
<span class="boring">}
</span></code></pre></pre>
<p>从这个节点树，我们看出，有<code>/user</code>和<code>/admin/:id</code>、<code>/admin/*id</code>这三种路由，就算路径相同，也会因为请求方法不同而保存为两个不同的节点（用 method 区分）。后面我们所有插入、查询的方法，都是围绕这样的节点树进行编写。</p>
<p>我们先来梳理一下插入逻辑：</p>
<ol>
<li>拆分路径，比如<code>/admin/:id</code>或者<code>/admin/index</code>，按照<code>/</code>符号拆分为<code>[admin,id]</code>和<code>[admin,index]</code>。</li>
<li>如果路径长度和层级相等，比如<code>/admin</code>和<code>/admin/:id</code>的层级分别是 1 和 2，则第一、二层的<code>pattern</code>分别为<code>/admin</code>和<code>/admin/:id</code>。</li>
<li>遍历匹配路径数组，如果已存在相应的节点如<code>/admin</code>且该节点<code>method</code>为 none，则在该节点上新增下一级。否则新增该节点。</li>
<li>路径含有<code>:</code>和<code>*</code>，则在新节点<code>part</code>字段插入相应参数，并且<code>is_match</code>标记为<code>true</code>。否则在<code>pattern</code>字段插入路径</li>
<li>在最后一层，将<code>pattern</code>和<code>method</code>赋值到节点上</li>
</ol>
<h3 id="拆分路径"><a class="header" href="#拆分路径">拆分路径</a></h3>
<p>把解析路径的函数提取出来，暂时放在<code>utils.rs</code> 中作为工具函数：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>//解析路径，排除&quot;&quot;号和*号之后的内容
pub fn parse_pattern(pattern: &amp;str) -&gt; Vec&lt;&amp;str&gt; {
    let list: Vec&lt;&amp;str&gt; = pattern.split('/').collect();
    let mut parts: Vec&lt;_&gt; = Vec::new();
    for item in list.into_iter() {
        if item != &quot;&quot; {
            parts.push(item);
            if item.starts_with('*') {
                break;
            }
        }
    }
    return parts;
}
<span class="boring">}
</span></code></pre></pre>
<p>下面开始为 <code>RouterNode</code> 节点树实现插入方法：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>impl RouterNode {

    ...
     //模糊匹配pattern组
    pub fn match_child_list(&amp;mut self, pattern: &amp;str) -&gt; Vec&lt;&amp;mut RouterNode&gt; {
        let mut children = Vec::new();
        for child in self.children.iter_mut() {
            if let Some(path) = &amp;child.pattern {
                if pattern.starts_with(&quot;/&quot;) &amp;&amp; path == pattern {
                    children.push(child);
                } else {
                    let raw_path = format!(&quot;/{}&quot;, pattern);
                    if path == &amp;raw_path {
                        children.push(child);
                    }
                }
            }
        }
        return children;
    }

    //合并兄弟节点
    pub fn merge(&amp;mut self, mut node: RouterNode) {
        if self.pattern == node.pattern {
            self.children.append(&amp;mut node.children)
        } else {
            self.children.push(node)
        }
    }

    //新增子节点
    pub fn new_child(&amp;mut self, part: &amp;str) -&gt; RouterNode {
        let mut children = RouterNode::new();
        if part.starts_with(':') || part.starts_with('*') {
            children.part = Some(String::from(part));
        } else {
            children.pattern = Some(format!(&quot;/{}&quot;, part));
        }
        children.is_match = part.starts_with(':') || part.starts_with('*');
        children
    }

    //插入节点
    pub fn insert(&amp;mut self, method: Method, path: &amp;str, parts: Vec&lt;&amp;str&gt;, height: usize) {
      if parts.len() == height {
            self.pattern = Some(String::from(path));
            self.method = Some(String::from(method.as_str()));
            return;
        }

        if let Some(&amp;part) = parts.get(height) {
            let level_path = format!(&quot;/{}&quot;, part);
            //模糊匹配level_path,获取同路径节点组
            let children = self.match_child_list(&amp;level_path);
            match children.len() {
                //没有同路径，则主节点新增该路径
                0 =&gt; {
                    let mut children = self.new_child(part);
                    children.insert(method, path, parts, height + 1);
                    self.merge(children);
                }
                _ =&gt; {
                    //检查其中是否有下级节点（method为none则存在下级节点）
                    let has_item = children.into_iter().find(|child| child.method == None);
                    match has_item {
                        //路由完整路径path与level_path不相等，则在该节点新增
                        Some(node) if path != &amp;level_path =&gt; {
                            node.insert(method.clone(), path, parts.clone(), height + 1);
                        }
                        _ =&gt; {
                            //在主节点新增
                            let mut children = self.new_child(part);
                            children.insert(method, path, parts, height + 1);
                            self.merge(children);
                        }
                    }
                }
            }
        }
    }
}
<span class="boring">}
</span></code></pre></pre>
<p>这里要特别注意<code>match_child_list</code>这个工具函数，它接收<code>&amp;mut self</code>作为节点，经过匹配之后返回<code>Option&lt;&amp;mut RouterNode&gt;</code>。同学们可以思考一下返回值为什么要这样写，能不能改成<code>Option&lt;RouterNode&gt;</code>或者其他形式。</p>
<h2 id="匹配查找-routernode-节点"><a class="header" href="#匹配查找-routernode-节点">匹配查找 RouterNode 节点</a></h2>
<p>在前面完成了节点的新增插入，我们来处理节点的匹配查找。</p>
<p>以<code>/admin/:id</code>和<code>/user/index</code>这俩个路由为例子，来梳理一下路由节点的匹配流程：</p>
<ol>
<li>先拆分路径，比如<code>/admin/123</code>或者<code>/user/index</code>，按照<code>/</code>符号拆分为<code>[admin,123]</code>和<code>[user,index]</code>。</li>
<li>递归匹配<code>pattern</code>是否有相应的路由如<code>/admin</code>、<code>/user</code>同时匹配<code>method</code>,有则获取该节点，无则返回<code>None</code>。</li>
<li>继续检查该节点，匹配下面的子节点，检查节点内 <code>part</code> 字段是否有动态参数（<code>:</code>和<code>*</code>），以及<code>pattern</code>是否有相应的路由如<code>/user/index</code>，同时匹配<code>method</code>。有则返回子节点，无则返回<code>None</code>。</li>
</ol>
<p>整个匹配流程梳理好了，我们来写两个工具函数<code>match_children</code>和<code>match_path</code>，分别用来匹配动态参数（<code>:</code>和<code>*</code>）以及<code>pattern</code>和<code>method</code>。</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>impl RouterNode {
   ...
    // 匹配part中的:和*的节点，用于查找
    pub fn match_children(&amp;self, part: &amp;str) -&gt; Vec&lt;&amp;RouterNode&gt; {
        let mut nodes: Vec&lt;_&gt; = Vec::new();

        for child in self.children.iter() {
            if let Some(p) = &amp;child.part {
                if p == part || child.is_match {
                    nodes.push(child)
                }
            }
        }
        return nodes;
    }

    // 递归匹配pattern和method的节点，用于查找
    pub fn match_path(&amp;self, path: &amp;str, method: Option&lt;String&gt;) -&gt; Option&lt;&amp;RouterNode&gt; {
        if let Some(parse_path) = &amp;self.pattern {
            if parse_path == path &amp;&amp; self.method == method.clone() {
                return Some(self);
            }
        }

        //遍历子路由
        if self.children.len() &gt; 0 {
            for child in self.children.iter() {
                if let Some(p) = child.match_path(path, method.clone()) {
                    return Some(p);
                }
            }
        }
        return None;
    }
}
<span class="boring">}
</span></code></pre></pre>
<p>接下来,得好好想想整个路由的匹配查找要怎样编写了。因为要用到递归和遍历。那代码书写顺序应该和前面的匹配流程相反。（别问我为什么，我也不知道，只是直觉如此-因为要实现递归！）</p>
<ol>
<li>检查节点内 <code>part</code> 字段，存在动态参数（<code>:</code>和<code>*</code>）则直接返回该节点</li>
<li>获取解析后的路径数组，遍历路径数组匹配<code>pattern</code>，先匹配完整路径<code>pattern</code>和<code>method</code>，存在则直接返回</li>
<li>检查节点<code>method</code> 是否为<code>none</code>，<code>method</code> 为 <code>none</code> 则存在下级节点, 然后递归函数，重复上述步骤</li>
<li>如果无法匹配到动态参数，则说明路由节点不存在，返回 <code>none</code></li>
</ol>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>impl RouterNode {
    ...
    //搜索节点
    pub fn search(&amp;self, raw_path: &amp;str, parts: Vec&lt;&amp;str&gt;, height: usize) -&gt; Option&lt;RouterNode&gt; {
        //检查是否匹配到最后一层或者有*号，有则返回当前节点的
        if let Some(part) = &amp;self.part {
            if parts.len() == height || part.starts_with('*') || part.starts_with(':') {
                let res = match self.pattern {
                    Some(_) =&gt; Some(self),
                    None =&gt; None,
                };
                return res;
            }
        }

        //遍历路由parts，检查pattern和part
        if let Some(&amp;part) = parts.get(height) {
            let router_path = format!(&quot;/{}&quot;, part);
            //先检查完整路径和方法是否匹配
            if let Some(node) = self.match_path(raw_path, method.clone()) {
                return Some(node);
                //检查其中是否有下级节点（method为none则存在下级节点）,然后递归下一层
            } else if let Some(node) = self.match_path(&amp;router_path, None) {
                for child in node.match_children(part) {
                    return child.search(method, raw_path, parts, height + 1);
                }
            }
        }

        return None;
    }
}
<span class="boring">}
</span></code></pre></pre>
<p>Trie 树的插入与查找都成功实现了，接下来我们将 Trie 树应用到路由中去吧。我们使用 <code>roots</code> 来存储每种请求方式的 Trie 树根节点。使用 <code>handlers</code> 存储每种请求方式的 <code>HandlerFun</code> 。<code>get_route</code> 函数中，还解析了<code>:</code>和<code>*</code>两种匹配符的参数，返回一个<code>map</code> 。例如<code>/admin/123</code> 匹配到<code>/admin/:id</code>，解析结果为：{id: &quot;123&quot;}，<code>/static/index.js</code> 匹配到<code>/static/\*filepath</code>，解析结果为<code>{filepath: &quot;index.js&quot;}</code>。</p>
<p>在 <code>HandlerFun</code> 中，希望能够访问到解析的参数，因此，需要对<code>AppContext</code>对象增加一个属性和方法，来提供对路由参数的访问。我们将解析后的参数存储到 <code>Params</code> 中，通过<code>c.Param(&quot;id&quot;)</code>的方式获取到对应的值。</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span>
<span class="boring">fn main() {
</span>pub struct Router {
    pub roots: HashMap&lt;String, RouterNode&gt;,
    pub handlers: HashMap&lt;String, Box&lt;Handler&gt;&gt;,
}
impl Router {
    pub fn new() -&gt; Self {
           Router {
               roots: HashMap::new(),
               handlers: HashMap::new(),
           }
    }

    //新增路由
    fn add_route&lt;F&gt;(mut self, pattern: &amp;str, method: Method, handler: F) -&gt; Router
    where
        F: Fn(&amp;mut AppContext) + Send + Sync + 'static,
    {
        //println!(&quot;路径: {:?}&quot;, pattern);
        let parts = parse_pattern(pattern);
        // println!(&quot;解析参数: {:#?}&quot;, parts);
        let mut node = match self.roots.get(method.as_ref()) {
            Some(mut node) =&gt; node.to_owned(),
            None =&gt; RouterNode::new(),
        };
        node.insert(pattern, parts, 0);
        // println!(&quot;1节点树：{:#?}&quot;, node);
        let key = format!(&quot;{}+{}&quot;, method.as_ref(), pattern);
        self.roots.insert(method.to_string(), node);
        self.handlers.insert(key, Box::new(handler));
        self
    }

    //获取路由
    pub fn get_route(&amp;self, method: &amp;Method, path: &amp;str) -&gt; (Option&lt;RouterNode&gt;, HashMap&lt;String, String&gt;) {
        let search_parts = parse_pattern(path);
        println!(&quot;路径{:#?}解析为 :{:#?}&quot;, path, search_parts);
        let mut params = HashMap::new();
        if let Some(root) = self.roots.get(method.as_str()) {
            println!(&quot;当前节点：{:#?}&quot;, root);
            let n = root.search(path, search_parts.clone(), 0);
            if let Some(ref node) = n {
                println!(&quot;获取匹配节点：{:#?}&quot;, n);
                if let Some(ref pattern) = node.pattern {
                    let parts = parse_pattern(pattern.as_str());
                    println!(&quot;解析节点参数{:#?}&quot;, parts);
                    for (index, part) in parts.into_iter().enumerate() {
                        if part.starts_with(':') {
                            params.insert(String::from(&amp;part[1..]), String::from(search_parts[index]));
                        }
                        if part.starts_with('*') &amp;&amp; part.len() &gt; 1 {
                            let v = search_parts.get(index..).unwrap().to_vec();
                            let mut s = v
                                .into_iter()
                                .map(|s| {
                                    let mut val = String::from(s);
                                    val.push_str(&quot;/&quot;);
                                    return val;
                                })
                                .collect::&lt;String&gt;();
                            s.pop();
                            params.insert(String::from(&amp;part[1..]), s);
                            break;
                        }
                    }
                };
            }
            return (n, params);
        } else {
            (None, params)
        }
    }
}
<span class="boring">}
</span></code></pre></pre>
<p>对比前面动态路由节点树的生成和解析匹配，现在新增路由和查询路由，那可是简单多了。但是吧，为了处理参数，也是费了我不少功夫。因为 rust 处理字符串实在是麻烦！</p>
<p>在调用匹配到的 <code>handler</code> 前，将解析出来的路由参数赋值给了 <code>c.Params</code>。这样就能够在 <code>handler</code> 中，通过 <code>AppContext</code> 对象访问到具体的值了。</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>async fn handler(addr: SocketAddr, req: Request&lt;Body&gt;, router: Arc&lt;Router&gt;) -&gt; Result&lt;Response&lt;Body&gt;, Infallible&gt; {
    let mut context = AppContext::default();
    let (node, params) = router.get_route(req.method(), req.uri().path());
    println!(&quot;node:{:#?}, params:{:#?}&quot;, node, params);
	if let Some(node) = node {
        context.params = params;
        context.path = req.uri().path().to_string();
        context.method = req.method().clone().into();
        ...//上一章中的queries和headers等代码
        if let Some(handle) = router.routes.get(&amp;key) {
            println!(&quot;AppContext:{:#?}&quot;, context);
            (handle)(&amp;mut context);
            Ok(context.response)
        }
	} else {
        context.string(Some(StatusCode::NOT_FOUND), &quot;404 not found&quot;);
        Ok(context.response)
    }
}
<span class="boring">}
</span></code></pre></pre>
<h2 id="测试"><a class="header" href="#测试">测试</a></h2>
<p>下面来检验一下成果。 在<code>main.rs</code>中的 <code>main</code> 函数写上：</p>
<pre><pre class="playground"><code class="language-rust">#[tokio::main]
async fn main() {
    let handle_hello = |c: &amp;mut AppContext| c.string(None, &quot;hello world from handler&quot;);
    let get_hello = |c: &amp;mut AppContext| {
        let key = format!(&quot;hello world from post,query: {}&quot;, c.params.get(&quot;id&quot;).unwrap());
        return c.string(None, &amp;key);
    };
    let  router = Router::new()
        .get(&quot;/user&quot;, get_hello)
        .post(&quot;/user&quot;, handle_hello)
        .patch(&quot;/user&quot;, handle_hello)
        .post(&quot;/admin/:id&quot;, get_hello)
        .get(&quot;/user/*id&quot;, handle_hello);;

    // Run the server like above...
    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));

    server::run(addr, router).await;
}
</code></pre></pre>
<p>打开浏览器，访问一下上面的路由，可以看到相应内容。</p>
<p>同时，可以在终端查看生成的节点树如下：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>当前节点: RouterNode {
    pattern: None,
    part: None,
    children: [
        RouterNode {
            pattern: Some(
                &quot;/user&quot;,
            ),
            part: None,
            children: [],
            is_match: false,
            hooks: [],
            method: Some(
                &quot;GET&quot;,
            ),
        },
        RouterNode {
            pattern: Some(
                &quot;/user&quot;,
            ),
            part: None,
            children: [],
            is_match: false,
            hooks: [],
            method: Some(
                &quot;POST&quot;,
            ),
        },
        RouterNode {
            pattern: Some(
                &quot;/user&quot;,
            ),
            part: None,
            children: [],
            is_match: false,
            hooks: [],
            method: Some(
                &quot;PATCH&quot;,
            ),
        },
        RouterNode {
            pattern: Some(
                &quot;/admin&quot;,
            ),
            part: None,
            children: [
                RouterNode {
                    pattern: Some(
                        &quot;/admin/:id&quot;,
                    ),
                    part: Some(
                        &quot;:id&quot;,
                    ),
                    children: [],
                    is_match: true,
                    hooks: [],
                    method: Some(
                        &quot;POST&quot;,
                    ),
                },
            ],
            is_match: false,
            hooks: [],
            method: None,
        },
        RouterNode {
            pattern: Some(
                &quot;/user&quot;,
            ),
            part: None,
            children: [
                RouterNode {
                    pattern: Some(
                        &quot;/user/*id&quot;,
                    ),
                    part: Some(
                        &quot;*id&quot;,
                    ),
                    children: [],
                    is_match: true,
                    hooks: [],
                    method: Some(
                        &quot;GET&quot;,
                    ),
                },
            ],
            is_match: false,
            hooks: [],
            method: None,
        },
    ],
    is_match: false,
    hooks: [],
    method: None,
}
<span class="boring">}
</span></code></pre></pre>
<p>至此，我们终于是把动态路由解析完成了。 <code>AppContext</code>这颗<code>金丹</code>总算是凝结成功！</p>
<p>这一章可以说是目前难度最大的内容了，定下这个路由节点树的数据结构。光是路由节点的插入和查询算法，我就断断续续花了一周时间来进行编写、修改。中间改了好几个版本，最终才写出这个相对简单易懂的算法。上面的流程只是我个人思考+实践后想到的算法，有兴趣的同学可以自己编写一个匹配路由算法。个人能力有限，该算法仅仅只是抛砖引玉，也欢迎各位来讨论和完善。最后，看在我这一周以来疯狂优化路由系统算法的份上，向大家要个赞，不过分吧😋。</p>

                    </main>

                    <nav class="nav-wrapper" aria-label="Page navigation">
                        <!-- Mobile navigation buttons -->
                            <a rel="prev" href="../../07_轮子系列/用rust从零开发一套web框架/用rust从零开发一套web框架：day2.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                                <i class="fa fa-angle-left"></i>
                            </a>

                            <a rel="next" href="../../07_轮子系列/用rust从零开发一套web框架/用rust从零开发一套web框架：day4.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                                <i class="fa fa-angle-right"></i>
                            </a>

                        <div style="clear: both"></div>
                    </nav>
                </div>
            </div>

            <nav class="nav-wide-wrapper" aria-label="Page navigation">
                    <a rel="prev" href="../../07_轮子系列/用rust从零开发一套web框架/用rust从零开发一套web框架：day2.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                        <i class="fa fa-angle-left"></i>
                    </a>

                    <a rel="next" href="../../07_轮子系列/用rust从零开发一套web框架/用rust从零开发一套web框架：day4.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                        <i class="fa fa-angle-right"></i>
                    </a>
            </nav>

        </div>




        <script type="text/javascript">
            window.playground_copyable = true;
        </script>


        <script src="../../elasticlunr.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="../../mark.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="../../searcher.js" type="text/javascript" charset="utf-8"></script>

        <script src="../../clipboard.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="../../highlight.js" type="text/javascript" charset="utf-8"></script>
        <script src="../../book.js" type="text/javascript" charset="utf-8"></script>

        <!-- Custom JS scripts -->


    </body>
</html>
